package hk.hku.hooku.servlet;

import hk.hku.hooku.db.EventDB;
import hk.hku.hooku.pojo.EventChoice;
import hk.hku.hooku.pojo.EventResult;
import hk.hku.hooku.pojo.EventVote;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UpdateVoteServlet
 */
public class UpdateVoteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateVoteServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String url=request.getParameter("url");
		if(url!=null){
			String voterEmail=request.getParameter("voterEmail");
			System.out.println(voterEmail);
			String voterName=request.getParameter("voterName");
			if(voterName==null){
				voterName="";
			}
			System.out.println(voterName);
			String note=request.getParameter("voterNote");
			if(note==null){
				note="";
			}
			System.out.println(note);
			String choiceIds=request.getParameter("selectChoices");
			System.out.println(choiceIds);
			String[] ids=choiceIds.split(",");
			//String[] ids=choiceIds.split(",");
			ArrayList<EventChoice> choices=new ArrayList<EventChoice>();
			EventVote vote=new EventVote(voterEmail, voterName, note, choices);
			
			boolean isSuccess=EventDB.createVote(url, vote, ids);
			
			PrintWriter writer=response.getWriter();
			if(isSuccess){
				writer.write("true");
			}else{
				writer.write("false");
			}
		}
	}

}
